import './TeacherCourseList.scss';
import CourseItem from './components/CourseItem/CourseItem';
import { useDispatch, useSelector } from 'react-redux';
import { fetchGetCourseList } from '@/store/modules/teacher';
import { useEffect, useState } from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, ConfigProvider, Input, message, InputNumber, Empty } from 'antd';
import { addCourseAPI, changeCourseInfoAPI } from '@/apis/teacher';

export default function TeacherCourseList() {

    const dispatch = useDispatch();
    const { user_status } = useSelector(state => state.user);
    const { courseList } = useSelector(state => state.teacher);
    const [courseArr, setCourseArr] = useState([]);
    const [checkList, setCheckList] = useState([]);
    const [hasChecked, setHasChecked] = useState(false);
    const [checkedItemNum, setCheckedItemNum] = useState(0);
    const [allChecked, setAllChecked] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [newCourseName, setNewCourseName] = useState('');
    const [newSubject, setNewSubject] = useState('');
    const [newPartNum, setNewPartNum] = useState(3);
    const [isChangeModalOpen, setIsChangeModalOpen] = useState(false);
    const [classId, setClassId] = useState(1);
    const [inviteCode, setInviteCode] = useState('');
    
    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleAddCourse = async () => {
        setLoading(true);
        const res = await addCourseAPI({
            classname: newCourseName,
            subject: newSubject,
            part_num: newPartNum
        }, user_status.token);
        console.log(res);
        setNewCourseName('');
        setNewPartNum(3);
        setNewSubject('');
        message.success('添加成功');
        window.location.reload();
        setLoading(false);
        setIsModalOpen(false);
    };

    const handleCancelChangeCourse = () => {
        setIsChangeModalOpen(false);
    }

    const showChangeModal = (class_id, oldname, oldsubject, curInviteCode) => {
        setClassId(class_id);
        setNewCourseName(oldname);
        setNewSubject(oldsubject);
        setInviteCode(curInviteCode);
        setIsChangeModalOpen(true);

    }

    const handleChangeCourse = () => {
        const res = changeCourseInfoAPI({
            class_id: classId,
            classname: newCourseName,
            subject: newSubject
        }, user_status.token);
        setClassId(0);
        setNewCourseName('');
        setNewSubject('');
        setIsChangeModalOpen(false);
        message.success('修改成功');
        window.location.reload();
    }

    const handleCancelAddCourse = () => {
        setIsModalOpen(false);
    };

    useEffect(() => {
        if (courseList.length !== 0) {
            setCheckList(Array(courseList.length).fill(false));
            // console.log(checkList);
        }
    }, [courseList]);

    const colorBox = [
        {
            dark: '#ee4863',
            light: '#f8b37f'
        },
        {
            dark: '#1781b5',
            light: '#0eb0c9'
        },
        {
            dark: '#55bb8a',
            light: '#bacf65'
        },
        {
            dark: '#61649f',
            light: '#c08eaf'
        },
    ]

    // 当组件渲染完成时执行一次
    useEffect(() => {

        const getCourseList = async function () {
            await dispatch(fetchGetCourseList(user_status.token));
            // setCheckList(data.map(() => false));
            // setCourseArr(data)
        }

        getCourseList();
    }, [])


    useEffect(() => {
        if (checkList.length !== 0) {
            setHasChecked(checkList.reduce((a, b) => a || b), false);
            setCheckedItemNum(checkList.reduce((a, b) => b ? ++a : a, 0));
            setAllChecked(checkList.reduce((a, b) => a && b), true);
        }

        // console.log(checkList);
    }, [checkList])


    const handleAllCheck = (e) => {
        setCheckList(checkList.map(() => e.target.checked))
    }

    const handleCancel = () => {
        setCheckList(checkList.map(() => false));
    }

    return (
        <div
            className="TeacherCourseList"
        >
            <nav
                style={{
                    height: hasChecked ? '40px' : '0'
                }}
            >
                <div className='all-check'>
                    <input
                        type='checkbox'
                        onChange={handleAllCheck}
                        checked={allChecked}
                        id='allcheckbox'
                    />
                    <label htmlFor='allcheckbox'>全选</label>
                    <div className='divide-line'></div>
                    <span>已选择{checkedItemNum}个课程</span>
                </div>
                <div className='delet-course'>
                    <button><DeleteOutlined /> 删除</button>
                    <div className='divide-line'></div>
                    <button onClick={handleCancel}>取消</button>
                </div>
            </nav>
            <main>
                {
                    courseList.length === 0 ||
                    (courseList[0].success?courseList.map(ele =>
                        <CourseItem
                            key={ele.id}
                            randbgk={colorBox[ele.id % 4]}
                            info={ele}
                            ifChecked={checkList[ele.id]}
                            onCheck={(key) => {
                                setCheckList(checkList.map((ele, index) => index === key ? !ele : ele));
                            }}
                            showChangeModal={showChangeModal}
                        />
                    ):<Empty 
                    className='empty'
                    image={Empty.PRESENTED_IMAGE_SIMPLE} 
                    description={
                        <span>
                            你还没有创建课程，点击右下角的图标创建
                        </span>
                    }
                />
                    )
                }
            </main>
            <ConfigProvider
                theme={{
                    token: {
                        // Seed Token，影响范围大
                        colorPrimary: '#2486b9',
                        borderRadius: 5,

                        // 派生变量，影响范围小
                        // colorBgContainer: '#f6ffed',
                    },
                }}
            >
                <Button
                    type="primary"
                    onClick={showModal}
                    className='add-course'
                >
                    <PlusOutlined />
                </Button>
                <Modal
                    title={<h3>添加课程</h3>}
                    open={isModalOpen}
                    onCancel={handleCancelAddCourse}
                    footer={[
                        <Button key="back" onClick={handleCancelAddCourse}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleAddCourse}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newcoursename'>请输入新建课程的名称</label>
                    <Input id='newcoursename' onInput={function (e) { setNewCourseName(e.target.value) }} value={newCourseName} />

                    <label htmlFor='subject'>请输入课程所属学科</label>
                    <Input id='subject' onInput={function (e) { setNewSubject(e.target.value) }} value={newSubject} />

                    <label>请输入课程章节数</label>
                    <InputNumber min={1} max={16} defaultValue={6} onChange={(value) => { setNewPartNum(value) }} value={newPartNum} />
                </Modal>
                <Modal
                    title={<h3>更改课程信息</h3>}
                    open={isChangeModalOpen}
                    onCancel={handleCancelChangeCourse}
                    footer={[
                        <Button key="back" onClick={handleCancelChangeCourse}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleChangeCourse}>
                            确认更改
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <div>
                        <span>课程邀请码：</span>
                        <span>{inviteCode}</span>
                    </div>
                    <label htmlFor='newcoursename'>请输入新课程名称</label>
                    <Input id='newcoursename' onInput={function (e) { setNewCourseName(e.target.value) }} value={newCourseName} />

                    <label htmlFor='subject'>请输入新学科名称</label>
                    <Input id='subject' onInput={function (e) { setNewSubject(e.target.value) }} value={newSubject} />

                </Modal>
            </ConfigProvider>
        </div>
    )
}